﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;

namespace RCMS.Entity
{
    public static class ExtensionMethod
    {

        public static DataTable ToDataTable(this IQueryable data)
        {
            var dt = new DataTable();
            var props = data.ElementType.GetProperties();

            foreach (var prop in props)
            {
                if (prop.PropertyType == typeof(DateTime?))
                    dt.Columns.Add(new DataColumn(prop.Name, typeof(DateTime)));
                else if (prop.PropertyType == typeof(int?))
                    dt.Columns.Add(new DataColumn(prop.Name, typeof(int)));
                else if (prop.PropertyType == typeof(decimal?))
                    dt.Columns.Add(new DataColumn(prop.Name, typeof(decimal)));
                else if (prop.PropertyType == typeof(bool?))
                    dt.Columns.Add(new DataColumn(prop.Name, typeof(bool)));
                else
                    dt.Columns.Add(new DataColumn(prop.Name, prop.PropertyType));
            }

            foreach (var obj in data)
            {
                var row = dt.NewRow();
                foreach (var prop in props)
                {
                    if (prop.GetValue(obj, null) == null)
                    {
                        // Don't set it to anything!!!
                    }
                    else
                    {
                        row[prop.Name] = prop.GetValue(obj, null);
                    }
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
    }
}
